<template>
  <view class="store-details-page">
    <!-- 门店图片轮播 -->
    <view class="store-images">
      <swiper class="swiper" indicator-dots="true" autoplay="true" interval="3000" duration="1000">
        <swiper-item v-for="(image, index) in storeImages" :key="index">
          <image :src="image" mode="aspectFill" class="store-image"></image>
        </swiper-item>
      </swiper>
    </view>
    
    <!-- 门店基本信息 -->
    <view class="store-info-section">
      <view class="store-header">
        <view class="store-name">{{storeInfo.name}}</view>
        <view class="store-rating">
          <text class="star filled" v-for="i in storeInfo.rating" :key="i">★</text>
          <text class="star" v-for="i in (5 - storeInfo.rating)" :key="i + storeInfo.rating">★</text>
          <text class="rating-text">{{storeInfo.rating}}分</text>
          <text class="sales-text">销量: {{storeInfo.monthlySales}}</text>
        </view>
      </view>
      
      <view class="store-address" @click="openMap">
		  <text class="address-text">{{storeInfo.address}}</text>
        <image src="@/img/车联网服务-03车辆维修-03门店详情_slices/plane@3x.png" class="address-icon"></image>
      </view>
      
      <view class="store-hours">
        <text class="hours-label">营业时间：</text>
        <text class="hours-text">{{storeInfo.businessHours}}</text>
      </view>
    </view>
    
    <!-- 服务项目 -->
    <view class="services-section">
      <view class="section-title">服务</view>
      <view class="services-list">
        <view class="service-item" v-for="(service, index) in storeServices" :key="index" @click="toggleServiceSelection(index)">
          <view class="service-checkbox" :class="{ 'checked': service.selected }">
            <text v-if="service.selected" class="checkmark">✓</text>
          </view>
          <view class="service-info">
            <text class="service-name">{{service.name}}</text>
            <text class="service-desc">{{service.description}}</text>
          </view>
          <view class="service-price">
            <text class="price-value">¥{{service.currentPrice}}</text>
            <text class="price-original" v-if="service.originalPrice">¥{{service.originalPrice}}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 门店评价 -->
    <view class="reviews-section">
      <view class="section-title">用户评价</view>
      <view class="reviews-list">
        <view class="review-item" v-for="(review, index) in storeReviews" :key="index">
          <view class="review-header">
            <image :src="review.avatar" class="user-avatar"></image>
            <view class="review-info">
              <text class="user-name">{{review.userName}}</text>
              <view class="review-rating">
                <text class="star filled" v-for="i in review.rating" :key="i">★</text>
                <text class="star" v-for="i in (5 - review.rating)" :key="i + review.rating">★</text>
              </view>
            </view>
            <text class="review-date">{{review.date}}</text>
          </view>
          <text class="review-content">{{review.content}}</text>
        </view>
      </view>
    </view>
    
    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <button class="cart-btn" @click="showServiceOrder">
        <text>购物车({{selectedServicesCount}})</text>
      </button>
      <button class="confirm-btn" @click="confirmSelectedServices">确认已选服务</button>
    </view>
    
    <!-- 服务订单弹窗 -->
    <view class="service-order-overlay" v-if="showServiceOrderModal" @click="closeServiceOrder">
      <view class="service-order-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">服务订单</text>
          <text class="close-btn" @click="closeServiceOrder">×</text>
        </view>
        
        <view class="modal-content">
          <view class="order-service-item" v-for="(service, index) in storeServices" :key="index" @click="toggleServiceSelection(index)">
            <view class="service-checkbox" :class="{ 'checked': service.selected }">
              <text v-if="service.selected" class="checkmark">✓</text>
            </view>
            <view class="service-info">
              <text class="service-name">{{service.name}}</text>
            </view>
            <view class="service-price">
              <text class="price-value">¥{{service.currentPrice}}</text>
            </view>
          </view>
        </view>
        
        <view class="modal-footer">
          <view class="total-price">
            <text class="total-label">合计:</text>
            <text class="total-value">¥ {{totalPrice}}</text>
          </view>
          <button class="confirm-order-btn" @click="confirmSelectedServices">确认已选服务</button>
        </view>
      </view>
    </view>
    
		
	</view>
</template>

<script>
import { maintenanceMerchantApi, maintenanceServiceApi, userApi } from '@/api/index.js';

	export default {
		data() {
			return {
      loading: false,
      loadingServices: false,
      loadingReviews: false,
      storeId: null,
      storeInfo: {
        id: null,
        name: "",
        rating: 5,
        monthlySales: 0,
        serviceTime: 0,
        satisfactionRate: 0,
        address: "",
        businessHours: "",
        phone: "",
        longitude: 113.230000,
        latitude: 35.250000,
        description: ""
      },
      storeImages: [
        require("@/img/车辆维修/维修厂1.jpeg"),
        require("@/img/车辆维修/维修厂1.jpeg"),
        require("@/img/车辆维修/维修厂1.jpeg")
      ],
      showServiceOrderModal: false, // 控制服务订单弹窗显示
      storeServices: [],
      storeReviews: []
    }
  },
  
  computed: {
    // 已选择的服务数量
    selectedServicesCount() {
      return this.storeServices.filter(service => service.selected).length;
    },
				
    // 总价格
    totalPrice() {
      return this.storeServices
        .filter(service => service.selected)
        .reduce((total, service) => total + parseInt(service.currentPrice), 0);
    }
  },
  
  onLoad(options) {
    // 设置页面标题
    uni.setNavigationBarTitle({
      title: '门店详情'
    });
    
    console.log('carMaintenanceDetails页面加载，接收到的参数:', options);
    
    // 如果接收到门店数据，更新门店信息并加载详细数据
    if (options.storeData) {
      try {
        const storeData = JSON.parse(decodeURIComponent(options.storeData));
        console.log('接收到的门店数据:', storeData);
        
        // 更新门店信息
        this.storeInfo = this.formatStoreInfo(storeData);
        this.storeId = storeData.id;
        
        // 确保销量数据被正确传递
        console.log('从列表页接收到的门店数据:', storeData);
        console.log('格式化后的门店信息中的销量:', this.storeInfo.monthlySales);
        
        // 更新门店图片
        if (storeData.image) {
          this.storeImages[0] = storeData.image;
        }
        
        console.log('更新后的门店信息:', this.storeInfo);
        
        // 加载详细数据
        this.loadStoreDetails();
      } catch (e) {
        console.error('解析门店数据失败：', e);
        uni.showToast({
          title: '数据加载失败',
          icon: 'none'
        });
      }
    } else if (options.storeId) {
      // 如果只传递了门店ID，则需要先获取门店基本信息
      this.storeId = options.storeId;
      this.loadStoreInfo();
    } else {
      console.log('没有接收到门店数据');
      uni.showToast({
        title: '缺少门店信息',
        icon: 'none'
      });
    }
  },
  
		methods: {
    // 加载门店基本信息
    async loadStoreInfo() {
      try {
        this.loading = true;
        const response = await maintenanceMerchantApi.getMerchantDetail(this.storeId);
        
        if (response.code === 200 && response.data) {
          console.log('获取到的门店详情数据:', response.data);
          // 确保包含销量数据
          if (response.data.monthlySales === undefined) {
            console.warn('门店详情API未返回monthlySales字段，尝试单独获取');
            // 如果详情API没有返回销量，尝试单独获取
            try {
              const salesResponse = await maintenanceMerchantApi.getMerchantSales(this.storeId);
              if (salesResponse.code === 200) {
                response.data.monthlySales = salesResponse.data || 0;
              }
            } catch (salesError) {
              console.error('获取销量数据失败:', salesError);
              response.data.monthlySales = 0;
            }
          }
          this.storeInfo = this.formatStoreInfo(response.data);
          console.log('格式化后的门店信息:', this.storeInfo);
          await this.loadStoreDetails();
        } else {
          uni.showToast({
            title: '获取门店信息失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取门店信息失败:', error);
        uni.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },

    // 加载门店详细数据
    async loadStoreDetails() {
      await Promise.all([
        this.loadServices(),
        this.loadReviews()
      ]);
    },

    // 加载服务项目
    async loadServices() {
      try {
        this.loadingServices = true;
        const response = await maintenanceServiceApi.getServicesByMerchant(this.storeId);
        
        if (response.code === 200 && response.data) {
          this.storeServices = response.data.map(service => this.formatServiceData(service));
        }
      } catch (error) {
        console.error('获取服务项目失败:', error);
      } finally {
        this.loadingServices = false;
      }
    },

    // 加载用户评价
    async loadReviews() {
      try {
        this.loadingReviews = true;
        const response = await maintenanceMerchantApi.getMerchantEvaluates(this.storeId);
        
        if (response.code === 200 && response.data) {
          // 获取所有评价的用户信息
          const reviewsWithUserInfo = await Promise.all(
            response.data.map(async review => await this.formatReviewDataWithUser(review))
          );
          this.storeReviews = reviewsWithUserInfo;
        }
      } catch (error) {
        console.error('获取用户评价失败:', error);
      } finally {
        this.loadingReviews = false;
      }
    },

    // 格式化门店信息
    formatStoreInfo(merchant) {
      // 格式化营业时间
      let businessHours = '营业时间未设置';
      if (merchant.startTime && merchant.endTime) {
        businessHours = `周一至周日 ${merchant.startTime}-${merchant.endTime}`;
      } else if (merchant.businessHours) {
        businessHours = merchant.businessHours;
      }

      const formattedInfo = {
        id: merchant.id,
        name: merchant.name || '未知门店',
        rating: merchant.rate || 5, // 使用rate字段
        monthlySales: merchant.monthlySales || merchant.sales || 0, // 兼容不同的销量字段名
        serviceTime: merchant.serviceTime || 0,
        satisfactionRate: merchant.satisfactionRate || 98,
        address: merchant.address || '地址未设置',
        businessHours: businessHours,
        phone: this.generateDefaultPhone(merchant.id),
        longitude: parseFloat(merchant.longitude) || 113.230000,
        latitude: parseFloat(merchant.latitude) || 35.250000,
        description: merchant.description || '',
        distance: merchant.distance || '',
        time: merchant.time || ''
      };
      
      console.log('formatStoreInfo - 原始数据:', merchant);
      console.log('formatStoreInfo - 格式化后的销量:', formattedInfo.monthlySales);
      
      return formattedInfo;
    },

    // 格式化服务数据
    formatServiceData(service) {
      return {
        id: service.id,
        name: service.name || '未知服务',
        description: service.introduction || '暂无介绍',
        currentPrice: service.presentPrice || 0,
        originalPrice: service.originalPrice,
        selected: false,
        typeId: service.typeId,
        merchantId: service.mId
      };
    },

    // 格式化评价数据（带用户信息）
    async formatReviewDataWithUser(review) {
      let userName = `用户${review.userId}`; // 默认用户名
      let avatar = require("@/img/车辆维修/维修厂1.jpeg"); // 默认头像
      
      try {
        console.log('正在获取用户信息，用户ID:', review.userId);
        // 获取用户信息
        const userResponse = await userApi.getUserById(review.userId);
        console.log('用户API响应:', userResponse);
        
        if (userResponse.code === 200 && userResponse.data) {
          console.log('用户数据:', userResponse.data);
          // 优先使用 nickName，其次是 userName
          userName = userResponse.data.nickName || userResponse.data.userName || `用户${review.userId}`;
          console.log('最终用户名:', userName);
          // 如果用户有头像，使用用户头像
          if (userResponse.data.avatar) {
            avatar = userResponse.data.avatar;
          }
        } else {
          console.warn('用户API响应异常:', userResponse);
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
      
      return {
        id: review.id,
        userName: userName,
        avatar: avatar,
        rating: review.rate || 5,
        date: this.formatDate(review.time),
        content: review.content || '用户未留下评价内容'
      };
    },

    // 格式化评价数据（保留原方法作为备用）
    formatReviewData(review) {
      return {
        id: review.id,
        userName: `用户${review.userId}`,
        avatar: require("@/img/车辆维修/维修厂1.jpeg"), // 默认头像
        rating: review.rate || 5,
        date: this.formatDate(review.time),
        content: review.content || '用户未留下评价内容'
      };
    },

    // 生成默认电话号码
    generateDefaultPhone(merchantId) {
      const phoneMap = {
        15: '18893029302', // 伟业汽车保养场(人民路店)
        16: '18893029303', // 速修汽车保养中心  
        17: '18893029304'  // 专业汽车保养连锁店
      };
      
      return phoneMap[merchantId] || `1889302930${merchantId % 10}`;
    },



    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '';
      
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      
      return `${year}-${month}-${day}`;
    },

    // 打开地图导航
    openMap() {
      console.log('打开地图导航，门店信息:', this.storeInfo);
      
      // 跳转到导航页面
      uni.navigateTo({
        url: `/pages/maintenanceNavigation/maintenanceNavigation?destinationData=${encodeURIComponent(JSON.stringify(this.storeInfo))}`,
        success: () => {
          console.log('跳转到导航页面成功');
        },
        fail: (err) => {
          console.error('跳转到导航页面失败：', err);
          // 如果跳转失败，使用系统导航作为备选方案
          uni.openLocation({
            latitude: this.storeInfo.latitude,
            longitude: this.storeInfo.longitude,
            name: this.storeInfo.name,
            address: this.storeInfo.address,
            success: () => {
              console.log('打开系统导航成功');
            },
            fail: (err) => {
              console.error('打开系统导航失败：', err);
              uni.showToast({
                title: '打开导航失败',
                icon: 'none'
              });
            }
          });
        }
      });
    },
    
    // 切换服务选择状态
    toggleServiceSelection(index) {
      this.storeServices[index].selected = !this.storeServices[index].selected;
      console.log('切换服务选择状态:', this.storeServices[index].name, this.storeServices[index].selected);
    },
    
    // 显示服务订单弹窗
    showServiceOrder() {
      this.showServiceOrderModal = true;
      console.log('显示服务订单弹窗');
    },
    
    // 关闭服务订单弹窗
    closeServiceOrder() {
      this.showServiceOrderModal = false;
      console.log('关闭服务订单弹窗');
    },
    
    // 确认已选服务
    confirmSelectedServices() {
      const selectedServices = this.storeServices.filter(service => service.selected);
      
      if (selectedServices.length === 0) {
        uni.showToast({
          title: '请选择服务项目',
          icon: 'none'
        });
        return;
      }
      
      console.log('确认已选服务:', selectedServices);
      console.log('总价格:', this.totalPrice);
      
      // 跳转到确认订单页面，传递门店数据和已选服务
      const orderData = {
        storeInfo: this.storeInfo,
        selectedServices: selectedServices,
        totalPrice: this.totalPrice
      };
      
      uni.navigateTo({
        url: `/pages/confirmOrder/confirmOrder?orderData=${encodeURIComponent(JSON.stringify(orderData))}`,
        success: () => {
          console.log('跳转到确认订单页面成功');
          this.closeServiceOrder();
        },
        fail: (err) => {
          console.error('跳转到确认订单页面失败：', err);
          uni.showToast({
            title: '页面跳转失败',
            icon: 'none'
          });
        }
      });
    }
		}
	}
</script>

<style scoped>
.store-details-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

/* 门店图片轮播 */
.store-images {
  width: 100%;
  height: 400rpx;
  background-color: #fff;
}

.swiper {
  width: 100%;
  height: 100%;
}

.store-image {
  width: 100%;
  height: 100%;
}

/* 门店基本信息 */
.store-info-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.store-header {
  margin-bottom: 25rpx;
}

.store-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 15rpx;
}

.store-rating {
  display: flex;
  align-items: center;
}

.star {
  font-size: 28rpx;
  color: #ddd;
  margin-right: 5rpx;
}

.star.filled {
  color: #FFD700;
}

.rating-text {
  font-size: 28rpx;
  color: #666;
  margin-left: 10rpx;
}

.sales-text {
  font-size: 28rpx;
  color: #666;
  margin-left: 20rpx;
}

.store-address {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
  cursor: pointer;
  padding: 10rpx 0;
  /* 移除justify-content，让元素自然顺序排列 */
}

.address-icon {
  width: 32rpx;
  height: 32rpx;
  margin-left: 8rpx;
  flex-shrink: 0;
  /* 确保图标与文本垂直居中对齐 */
  align-self: center;
}

.address-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.4;
  /* 移除flex: 1，让文本自然宽度 */
}

.store-hours {
  display: flex;
  align-items: center;
}

.hours-label {
  font-size: 28rpx;
  color: #666;
  margin-right: 10rpx;
}

.hours-text {
  font-size: 28rpx;
  color: #333;
}

/* 服务项目 */
.services-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 25rpx;
}

.services-list {
  display: flex;
  flex-direction: column;
}

.service-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  cursor: pointer;
}

.service-item:last-child {
  border-bottom: none;
}

.service-checkbox {
  width: 40rpx;
  height: 40rpx;
  border: 2rpx solid #ddd;
  border-radius: 6rpx;
  margin-right: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.service-checkbox.checked {
  background-color: #007AFF;
  border-color: #007AFF;
}

.checkmark {
  color: #fff;
  font-size: 24rpx;
  font-weight: bold;
}

.service-info {
  flex: 1;
  margin-right: 20rpx;
}

.service-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.service-desc {
  font-size: 26rpx;
  color: #999;
  line-height: 1.4;
}

.service-price {
  display: flex;
  align-items: baseline;
  flex-direction: column;
  align-items: flex-end;
}



.price-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #ff6b35;
}

.price-original {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
  margin-top: 5rpx;
}

/* 用户评价 */
.reviews-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.reviews-list {
  display: flex;
  flex-direction: column;
}

.review-item {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.review-item:last-child {
  border-bottom: none;
}

.review-header {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
}

.user-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  margin-right: 15rpx;
  flex-shrink: 0;
}

.review-info {
  flex: 1;
}

.user-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 5rpx;
}

.review-rating {
  display: flex;
  align-items: center;
}

.review-date {
  font-size: 24rpx;
  color: #999;
}

.review-content {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
}

/* 底部操作栏 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #eee;
  display: flex;
  gap: 20rpx;
}

.cart-btn, .confirm-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cart-btn {
  background-color: #ff6b35;
  color: #fff;
}

.confirm-btn {
  background-color: #ff9500;
  color: #fff;
}

/* 自定义电话弹窗 */
.phone-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 1000;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}

.phone-dialog {
  width: 100%;
  background-color: #fff;
  border-radius: 16rpx 16rpx 0 0;
  overflow: hidden;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.phone-number {
  text-align: center;
  font-size: 28rpx;
  color: #333;
  padding: 40rpx 30rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #e5e5e5;
}

.call-btn, .cancel-btn {
  height: 110rpx;
  font-size: 28rpx;
  border: none;
  width: 100%;
  background-color: #fff;
  color: #333;
  border-bottom: 1rpx solid #e5e5e5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cancel-btn {
  border-bottom: none;
}

.call-btn:active, .cancel-btn:active {
  background-color: #f5f5f5;
}

/* 服务订单弹窗样式 */
.service-order-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 1000;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}

.service-order-modal {
  width: 100%;
  background-color: #fff;
  border-radius: 16rpx 16rpx 0 0;
  overflow: hidden;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  font-size: 40rpx;
  color: #999;
  cursor: pointer;
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-content {
  flex: 1;
  padding: 0 30rpx;
  overflow-y: auto;
}

.order-service-item {
  display: flex;
  align-items: center;
  padding: 25rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  cursor: pointer;
}

.order-service-item:last-child {
  border-bottom: none;
}

.modal-footer {
  padding: 30rpx;
  border-top: 1rpx solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-price {
  display: flex;
  align-items: center;
}

.total-label {
  font-size: 28rpx;
  color: #333;
  margin-right: 10rpx;
}

.total-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff6b35;
}

.confirm-order-btn {
  background-color: #ff9500;
  color: #fff;
  border: none;
  border-radius: 40rpx;
  padding: 20rpx 40rpx;
  font-size: 28rpx;
  cursor: pointer;
}
</style>
